package com.example.uniapp.activity.userHome;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.example.uniapp.R;
import com.example.uniapp.bean.CookbookBean;
import com.example.uniapp.bean.CookbookFoodBean;
import com.example.uniapp.bean.CookbookStepBean;
import com.example.uniapp.dao.CookbookDao;
import com.example.uniapp.dao.CookbookFoodDao;
import com.example.uniapp.dao.CookbookStepDao;
import com.example.uniapp.utils.FileImgUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 实现修改食谱的功能
 */
public class UserUpdateCookbookActivity extends AppCompatActivity {
    private ActivityResultLauncher<String> getContentLaucher;
    private Uri uri;
    private String cookbookId;
    private LinearLayout cookbookFoodLayout;
    private LinearLayout cookbookStepLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_update_cookbook);

        cookbookFoodLayout = findViewById(R.id.user_bottom_menu_update_cookbook_food);
        cookbookStepLayout = findViewById(R.id.user_bottom_menu_update_cookbook_step);

        Toolbar toolbar = this.findViewById(R.id.user_bottom_menu_update_cookbook_toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //获取界面中的各个组件
        ImageView imgView = this.findViewById(R.id.user_bottom_menu_update_cookbook_img);
        EditText nameText = this.findViewById(R.id.user_bottom_menu_update_cookbook_name);

        //获取数据
        Intent intent = getIntent();
        CookbookBean cookbookBean = (CookbookBean) intent.getSerializableExtra("cookbook");
        cookbookId = cookbookBean.getCookbookId();

        //载入数据
        Bitmap bitmap = BitmapFactory.decodeFile(cookbookBean.getCookbookImg());
        imgView.setImageBitmap(bitmap);
        nameText.setText(cookbookBean.getCookbookName());

        //载入食材数据
        List<CookbookFoodBean> cookbookFoodBeanList = CookbookFoodDao.getCookbookFoodByCookbookId(cookbookId);
        for(int i = 0; i < cookbookFoodBeanList.size(); i++) {
            addFoodInputItem(cookbookFoodBeanList.get(i));
        }

        //载入食谱步骤数据
        List<CookbookStepBean> cookbookStepBeanList = CookbookStepDao.getCookbookStepByCookbookId(cookbookId);
        for(int i = 0; i < cookbookStepBeanList.size(); i++) {
            addStepInputItem(cookbookStepBeanList.get(i));
        }

        //将食谱图片设置为默认图片
        Drawable imgDrawable = imgView.getDrawable(); //获取图片
        Bitmap defaultImgBitmap = ((BitmapDrawable) imgDrawable).getBitmap();

        //初始化文件选择器
        getContentLaucher=registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
            @Override
            public void onActivityResult(Uri result) {
                if(result!=null) {
                    imgView.setImageURI(result);
                    uri=result;
                }else {
                    Toast.makeText(UserUpdateCookbookActivity.this, "未选择食品图片", Toast.LENGTH_SHORT).show();
                }
            }
        });

        imgView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openGallery(view);
            }
        });

        //当点击按钮时的操作
        Button addCookbookButton = this.findViewById(R.id.user_bottom_menu_update_cookbook_update_button);
        addCookbookButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //提取各属性
                String name = nameText.getText().toString();

                //判断各属性是否都输入了
                if(name.isEmpty()) {
                    Toast.makeText(UserUpdateCookbookActivity.this, "请输入修改后的食品名", Toast.LENGTH_SHORT).show();
                }else {

                    Drawable imgdrawable = imgView.getDrawable();
                    Bitmap imgBitmap = ((BitmapDrawable) imgDrawable).getBitmap();

                    //判断是否修改添加食品图片
                    String imgPath;
                    if (imgBitmap.sameAs(defaultImgBitmap)) {
                        //如果二者相等，代表未修改食品图片
                        imgPath = cookbookBean.getCookbookImg();
                    }else {
                        imgPath = FileImgUtils.getImgName(); //获取图片存储路径
                        FileImgUtils.saveImageUriToFileImg(uri, UserUpdateCookbookActivity.this, imgPath); //保存图片
                    }

                    //判断所有的食材输入框是否有输入
                    Boolean foodMark = true;
                    List<String> foodNames = new ArrayList<>();
                    List<String> foodCounts = new ArrayList<>();
                    for(int i = 0; i < cookbookFoodLayout.getChildCount(); i++) {
                        View itemView = cookbookFoodLayout.getChildAt(i);
                        EditText foodNameEditText = itemView.findViewById(R.id.itemview_food_input_layout_food_name);
                        EditText foodCountEditText = itemView.findViewById(R.id.itemview_food_input_layout_food_count);

                        String foodName = foodNameEditText.getText().toString().trim();
                        String foodCount = foodCountEditText.getText().toString().trim();

                        if(foodName.isEmpty() || foodCount.isEmpty()) {
                            Toast.makeText(UserUpdateCookbookActivity.this, "有食材信息未输入", Toast.LENGTH_SHORT).show();
                            foodMark = false;
                        }else {
                            foodNames.add(foodName);
                            foodCounts.add(foodCount);
                        }
                    }

                    //判断所有的制作食谱步骤的输入框是否有输入
                    Boolean stepMark = true;
                    List<String> steps = new ArrayList<>();
                    for(int i = 0; i < cookbookStepLayout.getChildCount(); i++) {
                        View itemView = cookbookStepLayout.getChildAt(i);
                        EditText stepEditText = itemView.findViewById(R.id.itemview_step_input_layout_step);

                        String step = stepEditText.getText().toString().trim();

                        if(step.isEmpty()) {
                            Toast.makeText(UserUpdateCookbookActivity.this, "有制作食谱步骤信息未输入", Toast.LENGTH_SHORT).show();
                            stepMark = false;
                        }else {
                            steps.add(step);
                        }
                    }

                    if(foodMark) {
                        //运行到这，代表可以保存数据到数据库
                        //存入数据库
                        //首先确保输入的食材跟步骤没有重复，否则无法成功插入数据库
                        for(int i = 0; i < foodNames.size(); i++) {
                            for(int j = i + 1; j < foodNames.size(); j++) {
                                if(foodNames.get(i).equals(foodNames.get(j))) {
                                    Toast.makeText(UserUpdateCookbookActivity.this, "添加食谱失败", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            }
                        }
                        for(int i = 0; i < steps.size(); i++) {
                            for(int j = i + 1; j < steps.size(); j++) {
                                if(steps.get(i).equals(steps.get(j))) {
                                    Toast.makeText(UserUpdateCookbookActivity.this, "添加食谱失败", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            }
                        }
                        //运行到这就可以正常添加了
                        int cookbookFoodDelResult = CookbookFoodDao.deleteCookbookFood(cookbookBean.getCookbookId());
                        int cookbookStepDelResult = CookbookStepDao.deleteCookbookStep(cookbookBean.getCookbookId());
                        for(int i = 0; i < foodNames.size(); i++) {
                            CookbookFoodDao.addCookbookFood(cookbookBean.getCookbookId(), foodNames.get(i), foodCounts.get(i));
                        }
                        for(int i = 0; i < steps.size(); i++) {
                            CookbookStepDao.addCookbookStep(cookbookBean.getCookbookId(), steps.get(i));
                        }
                        int cookbookResult = CookbookDao.updateCookbook(cookbookBean.getCookbookId(), name, imgPath);
                        if (cookbookResult == 1 && cookbookFoodDelResult == 1 && cookbookStepDelResult == 1) {
                            Toast.makeText(UserUpdateCookbookActivity.this, "修改食谱成功", Toast.LENGTH_SHORT).show();

                            //修改结束返回
                            finish();
                        } else {
                            Toast.makeText(UserUpdateCookbookActivity.this, "修改食谱失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        });
    }

    private void openGallery(View v) {
        //打开文件选择器
        getContentLaucher.launch("image/*");
    }

    /**
     * 建立菜单
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.user_cookbook_delete, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 选择菜单
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.user_cookbook_menu_delete) {
            //删除
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("删除该食谱");
            builder.setMessage("您确定要删除该食谱吗？");
            builder.setCancelable(false);
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });
            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    int cookbookResult = CookbookDao.delCookbook(cookbookId);
                    int cookbookFoodResult = CookbookFoodDao.deleteCookbookFood(cookbookId);
                    if(cookbookResult == 1 && cookbookFoodResult == 1) {
                        Toast.makeText(UserUpdateCookbookActivity.this, "删除食谱成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }else {
                        Toast.makeText(UserUpdateCookbookActivity.this, "删除食谱失败", Toast.LENGTH_SHORT).show();
                    }
                    dialogInterface.dismiss();
                }
            });
            AlertDialog alertDialog = builder.create();
            alertDialog.show();
        }
        return super.onOptionsItemSelected(item);
    }

    private void addFoodInputItem(CookbookFoodBean cookbookFoodBean) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View itemView = inflater.inflate(R.layout.itemview_food_input_layout, cookbookFoodLayout, false);

        //获取组件
        EditText foodNameEditText = itemView.findViewById(R.id.itemview_food_input_layout_food_name);
        EditText foodCountEditText = itemView.findViewById(R.id.itemview_food_input_layout_food_count);
        ImageButton addFoodButton = itemView.findViewById(R.id.itemview_food_input_layout_add_food);
        ImageButton deleteFoodButton = itemView.findViewById(R.id.itemview_food_input_layout_delete_food);

        //填充数据
        foodNameEditText.setText(cookbookFoodBean.getCookbookFood());
        foodCountEditText.setText(cookbookFoodBean.getCookbookFoodCount());

        //添加按钮点击事件
        addFoodButton.setOnClickListener(view -> addFoodInputItem(new CookbookFoodBean()));
        deleteFoodButton.setOnClickListener(view -> cookbookFoodLayout.removeView(itemView));

        //添加到布局
        cookbookFoodLayout.addView(itemView);
        cookbookFoodLayout.requestLayout();
    }

    private void addStepInputItem(CookbookStepBean cookbookStepBean) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View itemView = inflater.inflate(R.layout.itemview_step_input_layout, cookbookStepLayout, false);

        //获取组件
        EditText stepEditText = itemView.findViewById(R.id.itemview_step_input_layout_step);
        ImageButton addStepButton = itemView.findViewById(R.id.itemview_step_input_layout_add_step);
        ImageButton deleteStepButton = itemView.findViewById(R.id.itemview_step_input_layout_delete_step);

        //填充数据
        stepEditText.setText(cookbookStepBean.getCookbookStep());

        //添加按钮点击事件
        addStepButton.setOnClickListener(view -> addStepInputItem(new CookbookStepBean()));
        deleteStepButton.setOnClickListener(view -> cookbookStepLayout.removeView(itemView));

        //添加到布局
        cookbookStepLayout.addView(itemView);
        cookbookStepLayout.requestLayout();
    }
}